package com.alstudio.utils.android.media.audio.recorder2;

import java.io.File;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.utils.android.ALFileManager;
import com.alstudio.utils.android.media.audio.recorder.ALAudioRecordCallback;
import com.alstudio.utils.android.media.audio.recorder.ALAudioRecorder;
import com.alstudio.utils.android.media.audio.recorder.ALAudioRecordTask.ALAudioRecordTaskCallback;
import com.alstudio.utils.android.media.audio.recorder.ALAudioRecorder.ALAudioRecordErroCode;
import com.alstudio.utils.log.ALLog;
import com.alstudio.view.toast.MyToastUtil;
import com.loovee.imaohu.R;

public class ALAudioRecordTask2 implements ALAudioRecordCallback {

	boolean isSend = false;
	boolean isTimeout = false;

	private PopupWindow pop = null;
	private View layout;
	private LinearLayout layout1, layout2;
	private ProgressBar progressBar;

	private File myRecAudioFile;
	private File myRecAudioDir;
	private long startTime = 0, endTime = 0;
	private int recordSecond = 0;

	// 录音管理器
	private ALAudioRecorder mRecorder;

	// 文件名称
	private static final String PREFIX = "videorecorder";
	// 音频文件格式
	private static final String EXTENSION = null;
	// 最长60S
	private final int MAX_DURATION = 60 * 1000;
	// 显示popwindow的布局
	private View parent;
	private View view4Ptt;

	private Context context;

	private ALAudioRecordTaskCallback mSaveCallback;

	public ALAudioRecordTask2(Context context, String savePath, View parent,
			View view4Ptt) {
		// TODO Auto-generated constructor stub
		this.parent = parent;
		this.context = context;
		this.view4Ptt = view4Ptt;
		initRecordWindow();
		mRecorder = new ALAudioRecorder(context, savePath, "", MAX_DURATION,
				this);
		view4Ptt.setOnTouchListener(chat_record_onTouchListener);
	}

	public void resetView4Ptt() {
		view4Ptt.setOnTouchListener(chat_record_onTouchListener);
	}

	public void disableView4Ptt() {
		view4Ptt.setOnTouchListener(null);
	}

	public void setSaveCallback(ALAudioRecordTaskCallback saveCallback) {
		this.mSaveCallback = saveCallback;
	}

	private void initRecordWindow() {
		layout = ALLocalEnv.getLocalEnv().getGlobalLayoutInflater()
				.inflate(R.layout.chat_record_layout, null);
		pop = new PopupWindow(layout, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);// 获取PopupWindow对象并设置窗体的大小
		pop.setFocusable(false);
		pop.setOutsideTouchable(false);
		pop.setBackgroundDrawable(new BitmapDrawable());
		// pop.setAnimationStyle(R.style.PopupAnimation);
		layout1 = (LinearLayout) layout.findViewById(R.id.record_layout1);
		layout2 = (LinearLayout) layout.findViewById(R.id.record_layout2);
		progressBar = (ProgressBar) layout.findViewById(R.id.recording_beat);
	}

	private void showRecordPopWindow() {
		pop.showAtLocation(parent, Gravity.CENTER, 0, 0); // 设置窗体的位置
	}

	private void dismissWindow() {
		pop.dismiss();
	}

	private void updateRecordingBeat(int percent) {
		progressBar.setProgress(percent);
	}

	@Override
	public void onRecording() {
		// TODO Auto-generated method stub
		ALLog.d("开始录音");
		recordSecond = 0;

	}

	@Override
	public void onRecordStop() {
		// TODO Auto-generated method stub
		ALLog.d("录音结束");
	}

	@Override
	public void onAudioError(ALAudioRecordErroCode code) {
		// TODO Auto-generated method stub
		recordSecond = 0;

		dismissWindow();
		switch (code) {
		case AL_AUDIO_RECORD_TYPE_ERROR_INIT_RECORDER_FAIL:
			break;
		case AL_AUDIO_RECORD_TYPE_ERROR_NO_EXTENAL_STORAGE:
			MyToastUtil.getInstance().showToastOnCenter(
					context.getString(R.string.TxtSdcardUnmound));
			break;
		case AL_AUDIO_RECORD_TYPE_ERROR_UNKONW:
			MyToastUtil.getInstance().showToastOnCenter(
					context.getString(R.string.TxtUnknowError));
			break;
		default:
			break;
		}
	}

	@Override
	public void onAudioAmplitudeChanged(int ratio) {
		// TODO Auto-generated method stub
		ALLog.d("起始录音强度为" + ratio);
		ratio = ratio * 100 / 32768;
		if (ratio > 100) {
			ratio = 100;
		}
		ALLog.d("录音强度为" + ratio);
		updateRecordingBeat(ratio);
	}

	@Override
	public void onAudioProgressChanged(int second) {
		// TODO Auto-generated method stub
		ALLog.d("录音时间到"+second);
		recordSecond = second;
	}

	@Override
	public void onAudioMaxDurationReached() {
		// TODO Auto-generated method stub
		dismissWindow();
		if (ALFileManager.isFileExsit(mRecorder.getFilePath())) {
//			if (isSend) 
			{
				// 发送数据
				ALLog.d("文件保存成功啦 " + mRecorder.getFilePath());
				if (mSaveCallback != null) {
					mSaveCallback.onAudioSaved(
							mRecorder.getFilePath(),
							recordSecond);
				}
			}
		}
	}

	private OnTouchListener chat_record_onTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {// 按下按钮不放
				isSend = true;
				startTime = System.currentTimeMillis();
				showRecordPopWindow();

				mRecorder.start();

			} else if (event.getAction() == MotionEvent.ACTION_UP
					|| event.getAction() == MotionEvent.ACTION_CANCEL) {// 释放按钮
				dismissWindow();
				mRecorder.stop();
				// if (!isTimeout)
				{
					// 开启音乐

					endTime = System.currentTimeMillis();
					if ((endTime - startTime) / 1000 > 1) {

						if (ALFileManager.isFileExsit(mRecorder.getFilePath())) {
							if (isSend) {
								// 发送数据
								ALLog.d("文件保存成功啦 " + mRecorder.getFilePath());
								if (mSaveCallback != null) {
									mSaveCallback.onAudioSaved(
											mRecorder.getFilePath(),
											recordSecond);
								}
							}
						}

					} else {
						myRecAudioFile = null;
						MyToastUtil
								.getInstance()
								.showToastOnCenter(
										context.getString(R.string.TxtAudioTimeTooShort));
					}
				}
			} else if (event.getAction() == MotionEvent.ACTION_MOVE) {// 滑动按钮
				Float y = event.getY();
				if (y < 0) {
					isSend = false;
					layout1.setVisibility(View.INVISIBLE);
					layout2.setVisibility(View.VISIBLE);
				} else {
					isSend = true;
					layout1.setVisibility(View.VISIBLE);
					layout2.setVisibility(View.INVISIBLE);
				}
			}

			return false;
		}
	};

}
